<?php

namespace common\service;

use common\model\EntityModel;
use support\SingletonTrait;
use think\module\Module;

/**
 * 剧集服务
 */
class EpisodeService
{
    use SingletonTrait;

    /**
     * 查询集列表
     * @param array $filter
     * @param string $fields
     * @return array
     */
    public function selectEpisode(array $filter, $fields = 'id,name,code')
    {
        $filter['module_id'] = module_by_code('episode')['id'];
        return model(EntityModel::class)
            ->where($filter)
            ->field($fields)
            ->order("LENGTH(code) asc,code asc")
            ->select();
    }

    /**
     * 查询集列表
     * @param string $fields
     * @return array
     */
    public function selectEpisodeMap(array $filter, $fields = 'id,name,code', $key = 'code', $v = null)
    {
        $list = $this->selectEpisode($filter, $fields);
        return array_column($list, $v, $key);
    }

    /**
     * 获得多个项目的集信息
     * @param array $episodeCodeGroupedByProject
     * @return array
     */
    public function getMultipleProjectEpisodes($episodeCodeGroupedByProject = [])
    {
        if (empty($episodeCodeGroupedByProject)) {
            return [];
        }
        $episodeQueryFilter = [];
        foreach ($episodeCodeGroupedByProject as $filterEpisodeProjectId => $filterEpisodeCodes) {
            $episodeQueryFilter[] = [
                "project_id" => $filterEpisodeProjectId,
                "code" => ["IN", implode(',', array_unique($filterEpisodeCodes))],
            ];
        }
        $episodeQueryFilter["_logic"] = "OR";
        $episodeMap = model(EntityModel::class)
            ->field("id,name,code,project_id")
            ->where([
                $episodeQueryFilter,
                'module_id' => Module::$moduleDictData['module_index_by_code']['episode']['id'],
                '_logic' => 'AND',
            ])
            ->select();
        // 集以项目进行分组
        $episodeMap = array_group_by($episodeMap, 'project_id');
        return array_map(function ($episodeList) {
            return array_column($episodeList, null, 'code');
        }, $episodeMap);
    }
}
